package com.xyd.controller;

import com.xyd.pojo.User;
import com.xyd.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getAllUser")
    public String getAllUser(Model model) {
        List<User> list = userService.getAll();
        model.addAttribute("list", list);
        return "main";
    }

    @RequestMapping("/userLogin")
    public String userLogin(HttpSession session, User user) {
        User u = userService.userLogin(user);
        if (u != null) {
            session.setAttribute("user", u);
            return "forward:/user/getAllUser.do";
        } else {
            return "redirect:/login.html";
        }
    }

    @RequestMapping("/toAdd")
    public ModelAndView toAdd() {
        return new ModelAndView("add");
    }

    @RequestMapping("/add")
    public String add(User user) {
        userService.addUser(user);
        return "redirect:/user/getAllUser.do";
    }

    @RequestMapping("/del/{id}")
    public String del(@PathVariable("id") int id) {
        userService.delUser(id);
        return "redirect:/user/getAllUser.do";
    }

    @RequestMapping("/get/{id}")
    public String getUser(@PathVariable("id") int id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("u", user);
        return "userEdit";
    }

    @RequestMapping("/updateUser")
    public String updateUser(User user) {
        userService.updateUser(user);
        return "redirect:/user/getAllUser.do";
    }


}
